#pragma once
#include <iostream>
#include <pthread.h>

// 封装锁
namespace MyMutexArea
{
    class MyMutex
    {
    public:
        MyMutex (const MyMutex&) = delete;
        const MyMutex& operator=(const MyMutex &) = delete;
        MyMutex()
        {
            int n = ::pthread_mutex_init(&_mutex, nullptr);
            if (n != 0)
            {
                std::cerr << "pthread_mutex_init error" << std::endl;
                exit(1);
            }
        }

        void Lock()
        {
            int n = ::pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                std::cerr << "pthread_mutex_lock error" << std::endl;
                return;
            }
        }

        void UnLock()
        {
            int n = ::pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                std::cerr << "pthread_mutex_unlock error" << std::endl;
                return;
            }
        }

        pthread_mutex_t* GetMutex()
        {
            return &_mutex;
        }

        ~MyMutex()
        {
            int n = ::pthread_mutex_destroy(&_mutex);
            if (n != 0)
            {
                std::cerr << "pthread_mutex_destroy error" << std::endl;
                exit(4);
            }
        }

    private:
        pthread_mutex_t _mutex;
    };

    class LockGuard
    {
    public:
        LockGuard(MyMutex &mutex) : _mutex(mutex)
        {
            _mutex.Lock();
        }
        ~LockGuard()
        {
            _mutex.UnLock();
        }

    private:
        MyMutex& _mutex;
    };
};